﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Best.SmartCms.Utility.JsonFormater
{
    /// <summary>
    /// 价格转换，2位小数
    /// </summary>
    public class CustomizePriceConverter : CustomCreationConverter<decimal>
    {
        /// <inheritdoc />
        public override bool CanWrite => true;

        /// <inheritdoc />
        public override decimal Create(Type objecType)
        {
            return 0;
        }

        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {
                if (value == null)
                {
                    writer.WriteNull();
                }
                else
                {
                    var formatted = Math.Round((decimal)value, 2);
                    writer.WriteValue(formatted);
                }
            }
            catch (Exception)
            {
                writer.WriteValue(0);
            }

        }

        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (decimal.TryParse(reader.Value?.ToString(), out var value))
            {
                return Math.Round(value, 2);
            }
            return 0;

        }
    }
}
